package com.mayikt.days06;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @ClassName ForkJoinTest
 * @Author 蚂蚁课堂余胜军 QQ644064779 www.mayikt.com
 * @Version V1.0
 **/
public class ForkJoinTest extends RecursiveTask<Long> {
    private Long start;
    private Long end;
    private Long max = 100L;

    public ForkJoinTest(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        // end =400 start=1
        Long sum = 0L;
        if (end - start < max) {

            System.out.println(Thread.currentThread().getName() + ",计算start:" + start + "," + end);
            for (Long i = start; i <= end; i++) {
                sum += i;
            }
        } else {
            // 继续拆分
            Long l = (start + end) / 2; //200
            ForkJoinTest left = new ForkJoinTest(start, l);
            left.fork();
            // 201-400
            ForkJoinTest rigt = new ForkJoinTest(l + 1, end);
            rigt.fork();

            try {
                sum=left.get()+rigt.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }


        }


        return sum;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinTest forkJoinTest = new ForkJoinTest(1L, 400L);
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> submit = forkJoinPool.submit(forkJoinTest);
        System.out.println(submit.get());
    }
}
